package com.scisoft.scan.control;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.depotoutchange.DOCOrderActivity;
import com.scisoft.scan.control.depotoutsale.DOSOrderActivity;
import com.scisoft.scan.control.enterdepot.EnterDepotOrderActivity;
import com.scisoft.scan.control.quickcheck.InitCheckActivity;
import com.scisoft.scan.control.quickcheck.QuickCheckActivity;
import com.scisoft.scan.control.rent.RentOrderActivity;
import com.scisoft.scan.control.returngoods.ReturnGoodsOrderActivity;
import com.scisoft.scan.control.shelves.ShelvesEditActivity;
import com.scisoft.scan.control.stock.EasyPartActivity;
import com.scisoft.scan.control.stock.PartInfoActivity;
import com.scisoft.scan.control.stockdistribute.StockDistributeActivity;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.MenuItemBean;
import com.scisoft.scan.dy.LoginActivity;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.control.check.CheckOrderActivity;
import com.scisoft.scan.control.delivery.DeliveryActivity;
import com.scisoft.scan.control.depot.DepotInfoActivity;
import com.scisoft.scan.control.pack.PackInfoActivity;
import com.scisoft.scan.control.shelves.ShelvesActivity;
import com.scisoft.scan.control.stock.StockActivity;
import com.scisoft.scan.db.LoginDBHelper;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.SysParameter;
import com.scisoft.scan.ws.WebServiceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainMenuActivity extends Activity {

    public String TAG = "Bugcao-Scan";

    //region 首页菜单栏导航
    //菜单网格布局控件
    private GridView mGridView;
    //扫描框
    private ClearEditText et_bar;
    //用户名称
    private TextView tv_userName;
    //用户账号
    private TextView tv_userId;
    //退出按钮
    private TextView tv_logoff;
    //版本号
    private TextView tv_version;
    //菜单列表
    private List<MenuItemBean> menuItemBeanList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_main_menu);

        //初始化扫码接口
        init();

        //版本号
        tv_version = findViewById(R.id.tv_version);
        tv_version.setText("当前版本号："+SysParameter.currentVersion);
        //用户
        tv_userName = findViewById(R.id.tv_userName);
        tv_userId = findViewById(R.id.tv_userId);
        //扫描框
        et_bar = findViewById(R.id.et_bar);
        //注销按钮
        tv_logoff = findViewById(R.id.tv_logoff);
        tv_logoff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginDBHelper helper = new LoginDBHelper(MainMenuActivity.this, "config.db", null, 1);
                helper.SetParm(LoginDBHelper.Parm_LoginState, "0");
                Intent intent = new Intent(MainMenuActivity.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        //搜索按钮
        ImageView iv_scan = findViewById(R.id.iv_scan);
        iv_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //输入条码
                String barCode = et_bar.getUpperText().toString();
                if (barCode == null || "".equals(barCode.trim())) {
                    Toast.makeText(MainMenuActivity.this, "请输入配件或者货架条码", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    try {
                        ScanData(barCode);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });

        //查询用户登录信息，查询用户菜单配置
        //CommonUtil.showPress(this);
        QueryUserTask queryUserTask = new QueryUserTask(MainMenuActivity.this);
        queryUserTask.execute();
    }

    //初始化菜单
    private void bindMenuData(Context context) {
        //初始化底部导航栏
        initBottomBar();
        //选择主页
        setCurrentTab(1);
        //设置主页菜单项
        mGridView = findViewById(R.id.MyGridView);
        List<HashMap<String, Object>> data = new ArrayList<>();
        int length = menuItemBeanList.size();
        for (int i = 0; i < length; i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("ItemImageView", menuItemBeanList.get(i).getImageRes());
            map.put("ItemTextView", menuItemBeanList.get(i).getItemName());
            data.add(map);
        }
        Log.d("BugCao", "菜单数据" + data);
        //为itme.xml添加适配器
        SimpleAdapter simpleAdapter = new SimpleAdapter(MainMenuActivity.this,
                data, R.layout.item, new String[]{"ItemImageView", "ItemTextView"}, new int[]{R.id.ItemImageView, R.id.ItemTextView});
        mGridView.setAdapter(simpleAdapter);
        //为mGridView添加点击事件监听器
        mGridView.setOnItemClickListener(new GridViewItemOnClick());
    }

    //定义点击事件监听器
    private static final int REQUEST_MENU_MORE = 0;

    public class GridViewItemOnClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
            Intent intent = null;
            if (position >= 0 && position < menuItemBeanList.size()) {
                int menuId = menuItemBeanList.get(position).itemId;
                switch (menuId) {
                    case MenuItemBean.MENU_CKZY:
                        //仓库作业
                        intent = new Intent(MainMenuActivity.this, DepotInfoActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_DB:
                        //打包
                        intent = new Intent(MainMenuActivity.this, PackInfoActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_WLFY:
                        //物流发运
                        intent = new Intent(MainMenuActivity.this, DeliveryActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_PDQD:
                        //盘点清单
                        intent = new Intent(MainMenuActivity.this, CheckOrderActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_HJGL:
                        //货架
                        intent = new Intent(MainMenuActivity.this, ShelvesActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_KCCX:
                        //库存查询
                        intent = new Intent(MainMenuActivity.this, StockActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_PJCX:
                        //配件查询
                        intent = new Intent(MainMenuActivity.this, EasyPartActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_KSPD:
                        //快速盘点
                        intent = new Intent(MainMenuActivity.this, QuickCheckActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_THQD:
                        //退货清点
                        intent = new Intent(MainMenuActivity.this, ReturnGoodsOrderActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_ZKRK:
                        //总库入库
                        intent = new Intent(MainMenuActivity.this, EnterDepotOrderActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_JHJL:
                        //借货捡料
                        intent = new Intent(MainMenuActivity.this, RentOrderActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_QCPD:
                        //期初盘点
                        intent = new Intent(MainMenuActivity.this, InitCheckActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_DBCK:
                        //调拨出库
                        intent = new Intent(MainMenuActivity.this, DOCOrderActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_LSCK:
                        //零售出库
                        intent = new Intent(MainMenuActivity.this, DOSOrderActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_KQFP:
                        //库区分配
                        intent = new Intent(MainMenuActivity.this, StockDistributeActivity.class);
                        startActivity(intent);
                        break;
                    case MenuItemBean.MENU_ZX:
                        //注销
                        LoginDBHelper helper = new LoginDBHelper(MainMenuActivity.this, "config.db", null, 1);
                        helper.SetParm(LoginDBHelper.Parm_LoginState, "0");
                        intent = new Intent(MainMenuActivity.this, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    //返回当前界面
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_MENU_MORE:
                //查询用户登录信息，查询用户菜单配置
                CommonUtil.showPress(this);
                QueryUserTask queryUserTask = new QueryUserTask(MainMenuActivity.this);
                queryUserTask.execute();
                break;
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        Log.d(TAG, "进入扫码");
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(MainMenuActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                    Toast.makeText(getApplicationContext(), msg = "无效二维码：" + barCode, Toast.LENGTH_LONG).show();
                } else if (barCodeBean.partBean != null) {
                    //配件跳转
                    Intent intent = new Intent(MainMenuActivity.this, PartInfoActivity.class);
                    intent.putExtra("partBean", barCodeBean.partBean);
                    startActivity(intent);
                } else if (barCodeBean.shelvesBean != null) {
                    //货架跳转
                    Intent intent = new Intent(MainMenuActivity.this, ShelvesEditActivity.class);
                    intent.putExtra("data", barCodeBean.shelvesBean);
                    startActivity(intent);
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //查询用户登录信息以及用户的菜单权限
    class QueryUserTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryUserTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //默认验证一次
                SysParameter.userInfo = WebServiceHelper.AccountCheck();
                //获取用户配置的菜单
                menuItemBeanList = new ArrayList<>();
                List<MenuItemBean> temp = WebServiceHelper.GetUserVisibleMenu(SysParameter.user, SysParameter.password);
                //根据用户权限初始化首页的可见菜单
                if (temp != null || temp.size() == 0) {
                    for (int i = 0; i < temp.size(); i++) {
                        MenuItemBean bean = temp.get(i);
                        if ("1".equals(bean.itemSelect)) {
                            menuItemBeanList.add(bean);
                        }
                    }
                }
                //MenuItemBean zxbean=new MenuItemBean(0,"1");
                //menuItemBeanList.add(zxbean);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                //设置登录界面的用户名信息
                tv_userName.setText(SysParameter.userInfo.userName);
                tv_userId.setText(SysParameter.userInfo.userId);
                //初始化菜单
                bindMenuData(mcontext);

            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //以下为扫码相关
    private ScanManager mScanMgr = null;//扫码接口

    //初始化
    private void init() {
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        registerReceiver(mResultReceiver, intFilter);
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result:com.symbol.datawedge.api.NOTIFICATION_ACTION
//        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result:com.symbol.datawedge.api.RESULT_ACTION
//        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
//        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
//        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "收到广播: " + intent.getAction());
            String action = intent.getAction();
//            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
//                // 处理扫码结果
//                try {
//                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
//                    et_bar.setText(decodedData);
//                    ScanData(decodedData);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    Toast.makeText(MainMenuActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
//                }
//            }
            if (ScanManager.ACTION_SEND_SCAN_RESULT.equals(action)) {
                byte[] bvalue1 = intent.getByteArrayExtra(ScanManager.EXTRA_SCAN_RESULT_ONE_BYTES);
                String svalue1 = null;
                try {
                    if (bvalue1 != null) {
                        svalue1 = new String(bvalue1, "GBK");
                        Log.d(TAG, svalue1);
                        ScanData(svalue1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(MainMenuActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };
    //endregion

    //region 底部菜单栏
    private LinearLayout lout_menu1;
    private LinearLayout lout_menu5;
    private LinearLayout l_1;
    private LinearLayout l_5;
    private ImageView iv_1;
    private ImageView iv_5;
    private TextView tv_1;
    private TextView tv_5;
    private int currentTab;

    private void initBottomBar() {
        l_1 = findViewById(R.id.l_1);
        l_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setCurrentTab(1);
            }
        });
        l_5 = findViewById(R.id.l_5);
        l_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setCurrentTab(5);
            }
        });
        iv_1 = findViewById(R.id.iv_1);
        iv_5 = findViewById(R.id.iv_5);
        tv_1 = findViewById(R.id.tv_1);
        tv_5 = findViewById(R.id.tv_5);
        lout_menu1 = findViewById(R.id.lout_menu1);
        lout_menu5 = findViewById(R.id.lout_menu5);
    }

    private void setCurrentTab(int ctab) {
        currentTab = ctab;
        switch (currentTab) {
            case 1:
                iv_1.setImageResource(R.drawable.ic_home_64_on);
                iv_5.setImageResource(R.drawable.ic_my_64_on);
                tv_1.setTextColor(getResources().getColor(R.color.title_background_color));
                tv_5.setTextColor(getResources().getColor(R.color.bottombar_text_color_off));
                lout_menu1.setVisibility(View.VISIBLE);
                lout_menu5.setVisibility(View.GONE);
                break;
            case 5:
                iv_1.setImageResource(R.drawable.ic_home_64_off);
                iv_5.setImageResource(R.drawable.ic_my_64_off);
                tv_1.setTextColor(getResources().getColor(R.color.bottombar_text_color_off));
                tv_5.setTextColor(getResources().getColor(R.color.title_background_color));
                lout_menu1.setVisibility(View.GONE);
                lout_menu5.setVisibility(View.VISIBLE);
                break;
        }
    }
    //endregion

}
